package com.yaorange.module.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yaorange.ma_util.util.Md5Util;
import com.yaorange.module.system.entity.dto.SysUserQueryDTO;
import com.yaorange.module.system.mapper.SysUserMapper;
import com.yaorange.module.system.service.SysUserService;
import com.yaorange.pojo.SysUser;
import com.yaorange.response.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Override
    public PageResult<SysUser> findAll(SysUserQueryDTO sysUserQueryDTO) {
        PageHelper.startPage(sysUserQueryDTO.getPageNum(),sysUserQueryDTO.getPageSize());
        log.info("开始查询用户列表"+sysUserQueryDTO.getPageNum() +":"+sysUserQueryDTO.getPageSize());
        List<SysUser> list = sysUserMapper.findAll(sysUserQueryDTO);
        log.info("查询用户列表结束"+list);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        PageResult<SysUser> page = new PageResult<>();
        page.setData(pageInfo.getList());
        page.setTotal(pageInfo.getTotal());
        log.info("返回分页结果"+ page.getData());
        return page;
    }

    @Override
    public void save(SysUser sysUser) {
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUser.setCreateBy(1L);
        sysUserMapper.save(sysUser);
    }

    @Override
    public SysUser findById(Integer id) {
        return sysUserMapper.findById(id);

    }

    @Override
    public void update(Integer id, SysUser userDetails) {
        userDetails.setUserPassword(Md5Util.md5(userDetails.getUserPassword()));
        userDetails.setUpdateTime(LocalDateTime.now());
        userDetails.setUserId(id);
        sysUserMapper.update(userDetails);
    }

    @Override
    public void deleteById(Integer id) {
        sysUserMapper.deleteById(id);
    }

    @Override
    public void grantRolesList(Long id,boolean isAdmin) {
        if (isAdmin){
            sysUserMapper.updateAdmin(id,1);
        }else {
            sysUserMapper.updateAdmin(id,0);
        }

    }

    @Override
    public SysUser findByUsername(String username) {
        return sysUserMapper.findByUsername(username);
    }
}
